<template>
    <n-spin :show="loading">
        <n-space vertical :size="12">
            <n-space justify="space-between">
                <n-space>
                    <n-button @click="doAdd">
                        <template #icon>
                            <n-icon :component="AddRound" />
                        </template>
                        添加
                    </n-button>
                    <n-button type="warning" :disabled="srows.length == 0" @click="doBatchDelete">
                        <template #icon>
                            <n-icon :component="DeleteForeverRound" />
                        </template>
                        删除
                    </n-button>
                </n-space>
                <n-space>
                    <n-form inline :model="param" :show-label="false" :show-feedback="false" ref="formRef">
                        <n-form-item>
                            <n-input v-model:value="param.query.name" style="width: 150px" clearable placeholder="模板名称" />
                        </n-form-item>
                        <n-form-item>
                            <n-input v-model:value="param.query.code" style="width: 150px" clearable placeholder="模板代码" />
                        </n-form-item>
                    </n-form>

                    <n-button @click="doQuery">
                        <template #icon>
                            <n-icon :component="YoutubeSearchedForRound" />
                        </template>
                        查询
                    </n-button>
                </n-space>
            </n-space>
            <n-data-table
                striped
                size="large"
                type="selection"
                :checked-row-keys="srows"
                :max-height="height"
                :min-height="items.length > 0 ? height : 0"
                :row-key="(row:any) => row.id"
                @update:checked-row-keys="onCheckRow"
                :columns="columns"
                :data="items"
            />
            <n-space justify="end">
                <n-pagination show-size-picker :page="param.pager.page" :page-size="param.pager.size" :page-count="pager.all" :page-sizes="[10, 25, 50, 100]" @update:page="onChangePage" @update:page-size="onChangeSize">
                    <template #prefix="{}">当前 {{ pager.now }} / {{ pager.all }} 页，共 {{ pager.row }} 条数据</template>
                </n-pagination>
            </n-space>
        </n-space>
        <Form :item="data" v-model:show="formActive" v-if="formActive" @refresh="execLoad"></Form>
        <View :item="data" v-model:show="viewActive" v-if="viewActive"></View>
        <Infos :item="data" v-model:show="infosActive" v-if="infosActive"></Infos>
        <Delete :items="datas" v-model:show="deleteActive" v-if="deleteActive" @refresh="execLoad"></Delete>
    </n-spin>
</template>

<script lang="ts" setup>
import { h, ref, computed, onActivated } from 'vue'
import { NSpace, NText, NIcon, NButton, NTag } from 'naive-ui'
import { AddRound, DeleteForeverRound, YoutubeSearchedForRound, InfoOutlined, EditNoteOutlined } from '@vicons/material'

import { useStore } from '@/store'
import { Http, Filters } from '@/libs'

import View from './View.vue'
import Form from './Form.vue'
import Delete from './Delete.vue'
import Infos from './Infos.vue'

const store = useStore()

const loading = computed(() => store.state.loading.flag)

const height = computed(() => store.state.browser.innerHeight - 310)

const columns = [
    {
        type: 'selection',
        fixed: 'left',
        align: 'center',
    },
    {
        title: '模板信息',
        key: 'name',
        width: 200,

        align: 'left',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            if (row.code) {
                comps[comps.length] = h(NTag, { bordered: false, size: 'small', type: 'warning' }, { default: () => row.code })
            }
            comps[comps.length] = h(NText, {}, { default: () => row.name })
            return h(NSpace, { wrap: false }, { default: () => comps })
        },
    },
    {
        title: '模板配置',
        key: 'type',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            comps[comps.length] = h(NTag, { bordered: false, size: 'small', type: 'primary' }, { default: () => (row.uget.flag ? '支持领取' : '禁止领取') })
            comps[comps.length] = h(NTag, { bordered: false, size: 'small', type: 'info' }, { default: () => (row.type === 1 ? '金额' : '折扣') })

            if (row.type === 1) {
                comps[comps.length] = h('span', {}, { default: () => `优惠${Filters.money(row.cash)}元` })
            } else {
                comps[comps.length] = h('span', {}, { default: () => `优惠${Filters.percent(row.dis)}%` })
            }
            if (row.max > 0) {
                comps[comps.length] = h('span', {}, { default: () => `最多抵扣${Filters.money(row.max)}元` })
            }
            if (row.min > 0) {
                comps[comps.length] = h('span', {}, { default: () => `订单满${Filters.money(row.min)}元时可用` })
            }

            return h(NSpace, { wrap: false }, { default: () => comps })
        },
    },
    {
        title: '发放统计',
        key: 'summ',
        align: 'center',
        width: 200,
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            comps[comps.length] = h('span', {}, { default: () => `已领 ${row.summ.count} / 已用 ${row.summ.used}` })
            return h(NSpace, { wrap: false }, { default: () => comps })
        },
    },
    {
        title: '支持区域',
        key: 'areas',
        align: 'center',
        ellipsis: {
            tooltip: true,
        },
        render(row: any) {
            let comps: any[] = []
            row.areas.forEach((area: any) => {
                comps[comps.length] = h(NTag, { size: 'small', type: 'error' }, { default: () => area.name })
            })
            if (row.areas.length == 0) {
                comps[comps.length] = h(NTag, { size: 'small', type: 'info' }, { default: () => '全国范围' })
            }
            return h(NSpace, { wrap: false }, { default: () => comps })
        },
    },

    {
        title: '操作',
        key: 'actions',
        width: 270,
        align: 'left',
        fixed: 'right',
        render(row: any) {
            return h(
                NSpace,
                { justify: 'start' },
                {
                    default: () => [
                        h(
                            NButton,
                            {
                                size: 'small',
                                onClick: () => {
                                    srows.value = []
                                    data.value = row
                                    viewActive.value = true
                                },
                            },
                            { default: () => '详情', icon: () => h(NIcon, {}, { default: () => h(InfoOutlined, {}, {}) }) }
                        ),
                        h(
                            NButton,
                            {
                                size: 'small',
                                onClick: () => {
                                    srows.value = []
                                    data.value = row
                                    formActive.value = true
                                },
                            },
                            { default: () => '编辑', icon: () => h(NIcon, {}, { default: () => h(EditNoteOutlined, {}, {}) }) }
                        ),
                        h(
                            NButton,
                            {
                                size: 'small',
                                onClick: () => {
                                    srows.value = []
                                    data.value = row
                                    infosActive.value = true
                                },
                            },
                            { default: () => '列表', icon: () => h(NIcon, {}, { default: () => h(EditNoteOutlined, {}, {}) }) }
                        ),
                    ],
                }
            )
        },
    },
]

const srows = ref<string[]>([])

const onCheckRow = (keys: string[]) => {
    srows.value = keys
}

const onChangeSize = (size: number) => {
    param.value.pager.page = 1
    param.value.pager.size = size
    execLoad()
}

const onChangePage = (page: number) => {
    param.value.pager.page = page
    execLoad()
}

const param = ref({
    query: {
        code: '',
        uget: undefined,
        mchid: '',
        name: '',
    },
    pager: {
        page: 1,
        size: 10,
        time: new Date().getTime(),
    },
})

const pager = ref({
    now: 1,
    row: 0,
    all: 0,
    fms: 0,
})
const items = ref([])

const doQuery = () => {
    param.value.pager.page = 1
    execLoad()
}

const execLoad = () => {
    Http.post('/ops/opx/coupon/tmpl/list', param.value).then(resp => {
        if (resp.stat.err > 0) {
            return
        }
        if (resp.data.pager.now == 1) {
            param.value.pager.time = resp.data.pager.fms
        }
        srows.value = []
        pager.value = resp.data.pager
        items.value = resp.data.items
    })
}

const data = ref<any>({})

const datas = ref<any[]>([])

const doAdd = () => {
    data.value = undefined
    formActive.value = true
}

const doBatchDelete = () => {
    datas.value = items.value.filter((v: any) => srows.value.includes(v.id))
    deleteActive.value = true
}

const formActive = ref(false)
const viewActive = ref(false)
const deleteActive = ref(false)
const infosActive = ref(false)

onActivated(() => {
    execLoad()
})
</script>
